import { $ } from "../utils/utils";
import { mod360 } from "../utils/translate";
import { ref, onMounted, type Ref } from "vue";

// 将组合中的各个子组件拆分出来，并计算它们新的 style
export function decomposeComponent(component, editorRect, parentStyle) {
  // const componentRect = $(`#component${component.id}`).getBoundingClientRect();
  // 获取元素的中心点坐标

  const center = {
    x: parentStyle.left - editorRect.left + parentStyle.width / 2,
    y: parentStyle.top - editorRect.top + parentStyle.height / 2
  };

  component.style.rotate = mod360(component.style.rotate + parentStyle.rotate);
  component.style.width = (parseFloat(component.groupStyle.width) / 100) * parentStyle.width;
  component.style.height = (parseFloat(component.groupStyle.height) / 100) * parentStyle.height;
  // 计算出元素新的 top left 坐标
  component.style.left = center.x - component.style.width / 2;
  component.style.top = center.y - component.style.height / 2;
  component.groupStyle = {};
}

export const useDecompse = () => {
  const template: Ref<HTMLDivElement | null> = ref(null);
  function getEditor() {
    template.value = $("#visual-template-wrapper");
  }
  function decompose(component) {
    const parentStyle = { ...component.style };
    const components = component.propValue.components;
    const editorRect = template.value.getBoundingClientRect();

    components.forEach(component => {
      decomposeComponent(component, editorRect, parentStyle);
    });
    return components;
  }
  onMounted(() => {
    getEditor();
  });
  return {
    decompose
  };
};
